﻿using System;
using System.Text;
using Org.BouncyCastle.Utilities.Encoders;

namespace GmSm.Lib
{
    public class SM4Utils
    {
        public String secretKey = "";
        public bool hexString = true;
        public byte[] secretKeyBuff;

        /// <summary>
        /// 国密加密算法，改自java demo
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public String Encrypt_ECBV2(String plainText)
        {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;

            sbyte[] keyBytes=null;
            if (hexString)
            {
                keyBytes = ByteUtils.HexStringToByteArray(secretKey);
            }
            else
            {
                // keyBytes = Encoding.ASCII.GetBytes(secretKey);
            }

            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            sbyte[] encrypted = sm4.sm4_crypt_ecb(ctx, ByteUtils.convert(Encoding.UTF8.GetBytes(plainText)));

            String cipherText =Convert.ToBase64String(ByteUtils.convert(encrypted));
            return cipherText;
        }

        /// <summary>
        /// 国密解密算法，改自java demo
        /// </summary>
        /// <param name="cipherText"></param>
        /// <returns></returns>
        public String Decrypt_ECBV2(String cipherText)
        {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_DECRYPT;

            sbyte[] keyBytes = null;
            if (hexString)
            {
                keyBytes = ByteUtils.HexStringToByteArray(secretKey);
            }
            else
            {
                //keyBytes = Encoding.ASCII.GetBytes(secretKey);
            }

            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            sbyte[] decrypted = sm4.sm4_crypt_ecb(ctx, ByteUtils.convert(Convert.FromBase64String(cipherText)));
            byte[] cipherText1 = ByteUtils.convert(decrypted);
            string orgStr = Encoding.Default.GetString(cipherText1);
            return orgStr;
        }
        
    }
}